﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DAO
{
    public class DataProvider
    {
        private string connectionString;
        private SqlConnection sqlCon;

        public DataProvider()
        {
            connectionString = "Persist Security Info=False;database=nguyentuankiet_CSDLWEBTMDT;server=112.78.2.26,1488;user id=nguyentuankiet_EM09;password=em09em09;Current Language=English;Connection Timeout=240";
            Open();
        }

        // Phương thức kết nối tới CSDL SQL Server
        public bool Open()
        {
            try
            {
                sqlCon = new SqlConnection(connectionString);
                if (sqlCon.State == ConnectionState.Closed)
                {
                    sqlCon.Open();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        // Phương thức ngắt kết nối tới CSDL
        public bool Close()
        {
            try
            {
                if (sqlCon.State == ConnectionState.Open)
                {
                    sqlCon.Close();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        // Phương thức thực thi lệnh SELECT
        public DataTable ExecuteQuery(string sqlStatement)
        {
            try
            {
                SqlDataAdapter da = new SqlDataAdapter(sqlStatement, sqlCon);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
            catch
            {
                return null;
            }
        }

        // Phương thức thực thi lệnh INSERT, UPDATE và DELETE
        public int ExecuteNonQuery(string sqlStatement)
        {
            try
            {
                Open();
                SqlCommand sqlCom = new SqlCommand(sqlStatement, sqlCon);
                sqlCom.ExecuteNonQuery();
                Close();
                return 1;
            }
            catch
            {
                return 0;
            }
        }
    }
}
